$(function(){

	$('#accordion').accordion({ //初始化accordion
		fillSpace:true,
		fit:true,
		border:false,
		animate:false,
		selected:false,
		onSelect:function(title,index){
			$.cookie('c_index_accordion_index_v', index, {expires: 30});
		}
	});

	$.ajax({
		type:"POST",
		url:'right_v2/menuAjax_queryMenusByUser.action',
		dataType:"json",
		data:{},
		success:function(msg){
			//show accordion menu
			showAccordion(msg);
			//set default panal extend
			var indexAccordion = $.cookie('c_index_accordion_index_v');
			if(indexAccordion==null)indexAccordion='0';
			$('#accordion').accordion('select', Number(indexAccordion) );
			//show tree menu
			showTree(msg);
			//手风琴、树菜单
			var menuType = $.cookie('c_index_menu_type_v');
			if(menuType==null)menuType='accordion';
			changeMenu(menuType);
		},
		error:function(er){
			window.parent.error(er);
			$("#queryBtn_Filter").removeAttr("disabled");
			$('#'+datagrid.datagridId).datagrid('loaded');
		}
	});

	//手风琴、树菜单
	$("#accordionBtn").click(function(){
		changeMenu('accordion');
		$.cookie('c_index_menu_type_v', 'accordion', {expires: 30});
	});
	$("#treeBtn").click(function(){
		changeMenu('tree');
		$.cookie('c_index_menu_type_v', 'tree', {expires: 30});
	});

	//窗口大小变化时自动调整
	resizeWest();
	setInterval(resizeWest,1000);// 注意函数名没有引号和括弧！

	//绑定tabs的右键菜单
	var tabTitle;
	$("#tabs").tabs({
		onContextMenu:function(e,title){
			e.preventDefault();
			tabTitle = title;

			/* 选中当前触发事件的选项卡 */
			$("#tabs").tabs("select",title);

			$("#tabsMenu").menu('show',{
				left:e.pageX,
				top:e.pageY
			});//.data("tabTitle",title);
		}
	});

	//实例化menu的onClick事件
	$("#tabsMenu").menu({
		onClick:function(item){
			CloseTab(this,item.name);
		}
	});

	//几个关闭事件的实现
	function CloseTab(menu, type) {
		var curTabTitle = tabTitle;//$(menu).data("tabTitle");
		var tabs = $("#tabs");

		if (type === "Close") {
			tabs.tabs("close", curTabTitle);
			return;
		}

		var allTabs = tabs.tabs("tabs");
		var closeTabsTitle = [];

		$.each(allTabs, function () {
			var opt = $(this).panel("options");
			if (opt.closable && opt.title != curTabTitle && type === "Other") {
				closeTabsTitle.push(opt.title);
			} else if (opt.closable && type === "All") {
				closeTabsTitle.push(opt.title);
			}
		});

		for (var i = 0; i < closeTabsTitle.length; i++) {
			tabs.tabs("close", closeTabsTitle[i]);
		}
	}


	onSelectTaskTab();
	//onSelectTab();

	//timer for issue declare
	timer4issueDeclare();
	setInterval(timer4issueDeclare,timer4issueDeclareDelay);
})
/*20200612 只需要查询count，有时间再改掉查询列表的方式*/
function timer4issueDeclare(){

	var _issueTipsId = $(".issueTipsId");

	// var url = _path+'/admin123/coding/owIssueDeclare/owIssueDeclareAjax_queryListBySearch.action';
	var url = _path+'/admin123/coding/owIssueDeclare/owIssueDeclareAjax_queryListCount.action';
	$.ajax({
		type:"POST",
		url:url,
		dataType:"json",
		data:{'page':1,'rows':1,'sortOrder':'desc','sortColumn':'id'},
		success:function(msg){
			// console.log(msg)
			_issueTipsId.html(msg.total);
		},
		error:function(er){
			if(er.responseText!='' && er.responseText.indexOf('date error')!=-1){
				alert(er.responseText);
			}else{
				if(er.responseText!='' && er.responseText.indexOf('登录')!=-1){
					alert('会话超时，请重新登录');
				}
			}
		}
	});
}

function onSelectTab(){
	$('#tabs').tabs({
		onSelect:function(title,index){
			var tbIframe = $("#"+title);
			try{
				tbIframe[0].contentWindow.datagrid_fresh();
			}catch(e){
			}
		}
	});
}


function onSelectTaskTab(){
	$('#tabs').tabs({
		onSelect:function(title,index){
			var tab = $('#tabs').tabs('getSelected');
			var tbId = tab.attr("id");
			if(tbId == '_taskId' || tbId=='_issueDeclareId') {
				refreshTaskTab(tbId);
			}

		}
	});
}
function refreshTaskTab(tbId){
	//获取tab的iframe对象
	var tbIframe = $("#"+tbId+" iframe:first-child");
	try{
		tbIframe[0].contentWindow.datagrid_fresh();
	}catch(e){
	}
}


/**
 * 添加任务时，自动刷新任务列表（如果任务列表是打开的）
 */
/*function onAddTask(){
	var exists = $('#tabs').tabs('exists','任务列表.');
	var pp = $('#tabs').tabs('getTab','任务列表.');
	if(!exists){
		exists = $('#tabs').tabs('exists','任务列表');
		pp = $('#tabs').tabs('getTab','任务列表');
		if(!exists){
			return;
		}
	}
	var tab = pp.panel('options'); // 相应的标签页（tab）对象
	//
	$('#tabs').tabs({
		onSelect:function(title,index){
			openTab();
		}
	});
}*/




//窗口大小变化时自动调整
var westHeightOut = 0;
function resizeWest(){
	var westHeight = $('#west').height();
	if(westHeightOut != westHeight){
		westHeightOut = westHeight;
		$('#accordionDiv').css("height",westHeight-32+'px');
		$.parser.parse($('#west'));
	}
}

//菜单切换
function changeMenu(name){
	if(name=='accordion'){
		$('#tree').hide();
		$('#accordionDiv').show();
		$.parser.parse($('#west'));
	}else if(name=='tree'){
		$('#tree').show();
		$('#accordionDiv').hide();
	}
}

function showAccordion(treeAll){
	$.each(treeAll,function(i,node1){
		var text = node1.text;
		var id = node1.id;
		var iconClass = node1.iconClass;
		if(iconClass==null)iconClass='';
		$('#accordion').accordion('add', {
			title: text,
			iconCls:iconClass,
			content: "<ul id='tree"+id+"'></ul>",
			selected: false
		});

		var icon = [];
		$("#tree"+id).tree({
			data:node1.children,
			lines:true,
			iconCls:"icon-save",
			onSelect:function(node){
				$(this).tree(node.state === 'closed' ? 'expand' : 'collapse', node.target);
			},
			onClick:function(node){
				if(node.url!=null && node.type==10){
					Open(node.text,node.url,node.id);
					//Open(node.text+'-'+node.id,node.url,node.id);
				}
			},
			formatter: function (node) {
				icon.push({ "domId": node.domId, "iconCls":node.iconClass });
				return node.text;
			},
			onExpand:function(node){
				changeIcon(icon);
			},
			onCollapse:function(node){
				changeIcon(icon);
			}
		});

		//根据url修改图标，使用内联样式覆盖外部链接
		changeIcon(icon);
	});

	$.parser.parse();
}


function showTree(treeAll){

	var icon = [];
	$("#tree").tree({
		data:treeAll,
		lines:true,
		idField: 'id',
		treeField:'text',
		iconCls:"icon-save",
		onExpand:function(node){
			changeIcon(icon);
		},
		onSelect:function(node){
			$(this).tree(node.state === 'closed' ? 'expand' : 'collapse', node.target);
			changeIcon(icon);
		},
		onClick:function(node){
			if(node.url!=null && node.type==10){
				Open(node.text,node.url,node.id);
				//Open(node.text+'-'+node.id,node.url,node.id);
			}
		},
		formatter: function (node) {
			icon.push({ "domId": node.domId, "iconCls":node.iconClass });
			return node.text;
		},
		onLoadSuccess:function(){
			changeIcon(icon);

			/*var _tip = $('<span class="circle">198</span>');
			_tip.appendTo($("#_easyui_tree_90 .tree-title"));
			var _tip1 = $('<span class="circle">198</span>');
			_tip1.appendTo($("#_easyui_tree_32 .tree-title"));*/

		},
		onExpand:function(node){
			changeIcon(icon);
		},
		onCollapse:function(node){
			changeIcon(icon);
		}
	});
	$.parser.parse();
	$('#tree').hide();
}


function changeIcon(icon){
	$.each(icon, function (index, val) {
		$('#'+val.domId+' .tree-icon').removeClass("tree-file");
		$('#'+val.domId+' .tree-icon').removeClass("tree-folder");
		$('#'+val.domId+' .tree-icon').removeClass("tree-folder-open");
		$('#'+val.domId+' .tree-icon').addClass(val.iconCls);
	});
}

function Open(text,url){
	var jsonParam = {};
	jsonParam.url = _path+url;
	jsonParam.title = text;
	jsonParam.parameter1_iframedialog = '1';
	jsonParam.parameter2_iframedialog = '2';
	jsonParam.parameter3_iframedialog = '3';
	OpenNoProjectPath(jsonParam);
}

function Open(text,url,menu2Id){
	var index = text.indexOf('<span');
	if(index != -1){
		text = text.substring(0,index);
	}
	var jsonParam = {};
	jsonParam.url = _path+url;
	jsonParam.title = text;
	jsonParam.parameter1_iframedialog = menu2Id;
	jsonParam.parameter2_iframedialog = url;
	jsonParam.parameter3_iframedialog = '3';
	OpenNoProjectPath(jsonParam);
}

function getSelectedTabTitle(){
	var pp = $('#tabs').tabs('getSelected');
	var title = pp.panel('options').title; // 相应的标签页（tab）对象
	return title;
}


function OpenNoProjectPath(jsonParam){
	var text = jsonParam.title;
	if($("#tabs").tabs('exists',text)){
		$("#tabs").tabs('select',text);
	}else{
		var iframe = $('<iframe/>').attr({
			id : text,
			name : text,
			width : '100%',
			height : '100%',
			frameborder : 0,
			scrolling:'yes',
			src:jsonParam.url
		});

		var form = $('<form/>').attr({
			action:jsonParam.url,
			method:'POST',
			target:text
		});
		var input1 = $('<input/>').attr({
			type:'hidden',
			name:'parameter1_iframedialog',
			value:jsonParam.parameter1_iframedialog
		});
		var input2 = $('<input/>').attr({
			type:'hidden',
			name:'parameter2_iframedialog',
			value:jsonParam.parameter2_iframedialog
		});
		var input3 = $('<input/>').attr({
			type:'hidden',
			name:'parameter3_iframedialog',
			value:jsonParam.parameter3_iframedialog
		});
		form.append(input1);
		form.append(input2);
		form.append(input3);

		var win = $('<div/>').attr({
			width : '100%',
			height : '100%'
		}).appendTo('body');
		win.append(form);
		win.append(iframe);

		var tabId = "";
		if(jsonParam.title.indexOf('任务列表')!=-1) {
			tabId = "_taskId";
		}
		if( jsonParam.title.indexOf('待处理问题')!=-1 || jsonParam.title.indexOf('问题申报')!=-1 ) {
			tabId = "_issueDeclareId";
		}

		$("#tabs").tabs('add',{
			id:tabId,
			title:jsonParam.title,
			closable:true,
			fit:true,
			content:iframe
		});
		form.submit();
	}
}

function checkTimeout(){
	var url = _path+'/admin123/css/test/tree_data1.json';
	$.ajax({
		type:"POST",
		url:url,
		dataType:"json",
		success:function(msg){
			alert(JSON.stringify(msg));
		},
		error:function(er){
			//alert(er.responseText.trim());
			if(er.responseText!='' && er.responseText.indexOf('date error')!=-1){
				alert(er.responseText);
			}else{
				if(er.responseText!='' && er.responseText.indexOf('登录')!=-1){
					alert('会话超时，请重新登录');
				}
			}
		}
	});
}

function goOut(){
	//注销
	window.location.href=_path+'/j_spring_security_logout';
}

function goDesktopMode(){
	//注销
	window.location.href=_path+'/admin123/desktop/index.jsp';
}

function error(er){
	var errorText = er;
	try{
		if(er.responseText != undefined && er.responseText != ''){
			errorText = er.responseText;
		}
		if(errorText!='' && errorText.indexOf('please login first, it is a login page')!=-1){
			goOut();
		}
		else if(errorText!='' && errorText.indexOf('没有权限访问')!=-1){
			alert('没有权限访问');
		}
		else if(errorText!='' && errorText.indexOf('资源权限未分配')!=-1){
			alert('资源权限未分配');
		}
		else if(er.responseText!='' && er.responseText.indexOf('date error')!=-1){ //系统返回的错误信息
			alert(er.responseText);
		}
		else{
			alert(errorText);
		}
	}catch(Exception){
		alert(errorText);
	}
}

/*
 //只允许一个用户登录
 $(function(){
 var interval;
 function run(intervalTime){
 interval = setInterval(function(){
 $.ajax({
 type:"POST",
 url:"empAjax!singleUser.action",
 dataType:"json",
 data:{},
 success:function(msg){
 //alert(msg);
 },
 error:function(er){
 //alert(er.responseText);
 }
 })

 },intervalTime*1000);
 }
 var intervalTime = 20;
 clearTimeout(interval);
 run(intervalTime);
 })
 */
window.onbeforeunload = function (e) {
	e = e || window.event;
	var y = e.clientY
	if (y <= 0 || y >= Math.max(document.body.clientHeight, document.documentElement.clientHeight)){
		e.returnValue = "确认关闭浏览器窗口？！！";
	}
}
